package com.xiaoxing.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaoxing.domain.ResponseResult;
import com.xiaoxing.domain.entity.LoginUser;
import com.xiaoxing.domain.entity.User;
import com.xiaoxing.domain.vo.BlogUserLoginVo;
import com.xiaoxing.domain.vo.UserInfoVo;
import com.xiaoxing.enums.AppHttpCodeEnum;
import com.xiaoxing.service.CodeService;
import com.xiaoxing.service.UserService;
import com.xiaoxing.utils.*;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Objects;

/**
 * @Author: liyugang
 * Description: 发送短信业务类
 * @Date: created on 2023/7/27
 */
@Service
public class CodeServiceImpl implements CodeService {
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserService userService;

    /**
     * 发送验证码
     * @param
     * @return
     */
    @Override
    public ResponseResult sendCode(String phonenumber) {
        // 查询redis中的验证码是已存在
        String code = redisCache.getCacheObject(phonenumber);
        if (StringUtils.hasText(code)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.CODE_EXIST);
        }

        code = RandomNumberUntils.getCode();
        try {
            /**
             * 发送验证码给用户
             * phone 接受验证码的手机号
             * templateCode 短信模板id
             * code 验证码
             */
            CodeUtils.sendCode(phonenumber, code);
            redisCache.set(phonenumber, code, 3); // 设置验证码3分钟过期
            return ResponseResult.okResult();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(777,"验证码发送失败");
        }
    }

    /**
     * 查询缓存中的验证码
     * @param phone
     * @return
     */
    @Override
    public ResponseResult verifycode(String code,String phonenumber) {
        String code1 = redisCache.getCacheObject(phonenumber);
        if (StringUtils.hasText(code1)) {
            String cacheObject = redisCache.getCacheObject(phonenumber);
            if (cacheObject.equals(code)){
                LambdaQueryWrapper<User>wrapper=new LambdaQueryWrapper<>();
                wrapper.eq(User::getPhonenumber,phonenumber);
                User one = userService.getOne(wrapper);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(one.getUserName(),one.getPassSave());
                Authentication authenticate = authenticationManager.authenticate(authenticationToken);
                //获取userid 生成token
                LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
                String userId = loginUser.getUser().getId().toString();
                String jwt = JwtUtil.createJWT(userId);
                //把用户信息存入redis
                redisCache.setCacheObject("bloglogin:"+userId,loginUser);

                //把token和userinfo封装 返回
                //把User转换成UserInfoVo
                UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
                BlogUserLoginVo vo = new BlogUserLoginVo(jwt,userInfoVo);
                return ResponseResult.okResult(vo);
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.CODE_ERROR);
            }
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.CODE_PASS);
        }
    }
}
